package com.robot.orders.controller;

import com.robot.orders.pojo.Orders;
import com.robot.orders.pojo.vo.OrdersRequestModel;
import com.robot.orders.pojo.vo.Payment;
import com.robot.orders.service.OrdersService;
import com.robot.orders.service.PayService;
import com.robot.orders.service.WeChatPayService;
import entity.Result;
import entity.StatusCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import util.IpUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;


/**
 * @author wuyunbin
 */
@RestController
@CrossOrigin
@RequestMapping("/pay")
public class PayController {
    @Autowired
    private OrdersService ordersService;

    @Autowired
    private WeChatPayService weChatPayService;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private PayService payService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RequestMapping(value = "/pay", method = RequestMethod.POST)
    public Result pay(@RequestBody OrdersRequestModel ordersRequestModel) throws Exception {
        logger.info("=======ordersRequestModel==========");
        logger.info(ordersRequestModel.toString());
        logger.info("=======ordersRequestModel==========");

        if ("".equals(ordersRequestModel.getOrdersId().trim()) || ordersRequestModel.getOrdersId() == null) {
            return new Result(StatusCode.ERROR_ORDERS_ID_REQUIRED);
        }

        if (ordersRequestModel.getPayAmount() == null) {
            return new Result(StatusCode.ERROR_PAY_AMOUNT_REQUIRED);
        }

        //查找订单
        String ordersId=ordersRequestModel.getOrdersId();
        Orders orders = ordersService.findById(ordersId);
        if (orders == null) {
            //如果没有这个订单则写入订单
            logger.info("ordersRequestModel ordersId="+ordersRequestModel.getOrdersId());
            logger.info("ordersRequestModel memberId="+ordersRequestModel.getMemberId());
            ordersService.add(ordersRequestModel);
        }else{
            //已经存在这个订单，则更新
            ordersService.updateByRequestModel(ordersRequestModel);
        }

        //设置ip
        ordersRequestModel.setRequestIp(IpUtil.getIpAddr(httpServletRequest));

        logger.info(ordersRequestModel.toString());

        Payment payment = new Payment(ordersRequestModel.getPayment() + "");

        HashMap<String, String> result = payService.handler(payment, ordersRequestModel);


        logger.info("===========pay response===========");
        logger.info(ordersRequestModel.toString());
        logger.info(result.toString());
        logger.info("===========pay response===========");
//        这里处理一下result
        String error="error";
        logger.info("query orders ordersId="+ordersId);
        //推一个查询任务到mq
        rabbitTemplate.convertAndSend("query",ordersId);
        if (result.get(error) != null) {
            return new Result(StatusCode.FAIL_REQUEST, result);
        }
        return new Result(StatusCode.SUCCESS, result);
    }

    @RequestMapping(value = "/config",method = RequestMethod.POST)
    public Result config(@RequestBody HashMap<String,String> req) throws Exception{
        String url=req.get("url");
        return new Result(StatusCode.SUCCESS,payService.getConfig(url));
    }

    /**
     * 订单查询接口
     *
     * @param ordersId
     * @return
     */
    @RequestMapping(value = "/queryOrders/{ordersId}", method = RequestMethod.GET)
    public Result queryOrders(@PathVariable String ordersId) {
        if("".equals(ordersId.trim())){
            return new Result(StatusCode.ERROR_ORDERS_ID_REQUIRED);
        }
        logger.info("query orders ordersId="+ordersId);
        //推一个查询任务到mq
        rabbitTemplate.convertAndSend("query",ordersId);
        return new Result(StatusCode.SUCCESS_QUERY, weChatPayService.query(ordersId));
    }

    @RequestMapping(value = "/getOpenId/{code}", method = RequestMethod.GET)
    public Result getOpenId(@PathVariable String code) {
        return new Result(StatusCode.SUCCESS_GET, weChatPayService.getOpenId(code));
    }

}